package com.ordobill.webapp.common;

import java.io.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.upload.*;

import com.ibatis.sqlmap.client.*;
import com.ordobill.webapp.beans.SystemImg;

public class FileManager {
  
    public static final int BUFFER_SIZE = 8192;
    private static final String TARGET_DIR = Config.getInstance().getString("upload-file-location");
    private static Log log = LogFactory.getFactory().getInstance(FileManager.class);
    private static SqlMapClient sqlMap = SqlMapClientManager.getSqlMapClient();

    public static int fileUpload(FormFile file) throws Exception {

        if (file != null) {

            // Path Info
            //String destPath = DateUtil.getCurrentDate("yyyyMMdd");
            //String destDir = TARGET_DIR + "/" + destPath;

            String currentTime = Long.toString(System.currentTimeMillis()); 
            String fileRename = currentTime + "_" + file.getFileName();

            if (log.isDebugEnabled()) {
                log.debug("Dest dir      : " + TARGET_DIR);                
                log.debug("Original File : " + file.getFileName());
                log.debug("Rename   File : " + fileRename);
            }

            // Make Directory
            //File uploadDirectory = new File(TARGET_DIR);
            //uploadDirectory.mkdirs();

            // Write File
            String orgFileName = TARGET_DIR + "/" + fileRename;
            OutputStream bos = new FileOutputStream(orgFileName);
            int bytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            InputStream stream = file.getInputStream();
            while ((bytesRead = stream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            bos.flush();
            bos.close();
            stream.close();

            // Create Thumbnail File
            //String thumbFile = currentTime + "_thumb_" + file.getFileName();
            //String thumbFileName = destDir + "/" + thumbFile;

            //Thumbnail.createImage(orgFileName, thumbFileName);

            // Insert DB
            //FileImgStore bean = new FileImgStore();
            //bean.setNmFile(fileRename);
            //bean.setNmPath(destPath);
            //bean.setNmRealFile(file.getFileName());
            //bean.setNmThumbFile(thumbFile);
            //bean.setTpContent(file.getContentType());
            //bean.setSzFile(file.getFileSize());
            //
            //return (Integer) sqlMap.insert("FileImgStore.add", bean);
        }

        return 0;
    }
    
    /**
     * 파일업로드 유틸
     * @param file FormFile
     * @param sysimgUid System_Img테이블의 Sysimg_Uid값
     * @return int result
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public static int fileUpload(FormFile file , int sysimgUid) throws Exception {

        if (file != null) {

            String currentTime = Long.toString(System.currentTimeMillis()); 
            String filename = file.getFileName();

            if (log.isDebugEnabled()) {
                log.debug("Dest dir      : " + TARGET_DIR);                
                log.debug("Original File : " + file.getFileName());
                log.debug("Rename   File : " + filename);
            }

            // Write File
            String orgFileName = TARGET_DIR + "/" + filename;
            OutputStream bos = new FileOutputStream(orgFileName);
            int bytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            InputStream stream = file.getInputStream();
                while ((bytesRead = stream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bos.flush();
                bos.close();
                stream.close();

            // Insert DB
            SystemImg sysimgBean = new SystemImg();
            sysimgBean.setSysimgUid(sysimgUid);
            sysimgBean.setSysimgFile(filename);
            return (Integer) sqlMap.update("SystemImg.systemimgUpdateFile", sysimgBean);
        }

        return 0;
    }
    
    /**
     * 파일업로드 유틸
     * @param file FormFile
     * @param sysimgUid System_Img테이블의 Sysimg_Uid값
     * @return int result
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public static int fileUpload(FormFile file , int sysimgUid, String sysimgDiv) throws Exception {

        if (file != null) {

            String currentTime = Long.toString(System.currentTimeMillis()); 
            String filename = file.getFileName();

            if (log.isDebugEnabled()) {
                log.debug("Dest dir      : " + TARGET_DIR);                
                log.debug("Original File : " + file.getFileName());
                log.debug("Rename   File : " + filename);
            }
            
            //2010-01-13 정재우 실장님의 요청에 의해 추가했습니다.
            //앞부분에 BR인지 EQ인지에대해서 구분하도록합니다.
            filename = sysimgDiv+"_"+filename;

            // Write File
            String orgFileName = TARGET_DIR + "/" +filename;
            OutputStream bos = new FileOutputStream(orgFileName);
            int bytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            InputStream stream = file.getInputStream();
                while ((bytesRead = stream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bos.flush();
                bos.close();
                stream.close();

            // Insert DB
            SystemImg sysimgBean = new SystemImg();
            sysimgBean.setSysimgUid(sysimgUid);
            sysimgBean.setSysimgFile(filename);
            return (Integer) sqlMap.update("SystemImg.systemimgUpdateFile", sysimgBean);
        }

        return 0;
    }
    
    public static int fileDelete(String sysimgFile) throws Exception{
    	log.debug("Now is deleting ===========>"+sysimgFile);
    	if(sysimgFile != null){
    		try{
    		    File deleteFile = new File(TARGET_DIR+"/"+sysimgFile);
    		         deleteFile.delete();
    		         return 1;
    		}catch(Exception e){
    			log.debug(e);
    			return -1;
    		}
    	}
    	return -1;
    }
}
